<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\ApiController;
use App\Http\Controllers\Controller;
use App\Http\Resources\ContentResource;
use App\Http\Resources\MessageResource;
use App\Models\Message;
use App\Models\UserReadMessage;
use Illuminate\Http\Request;

class MessageController extends ApiController
{
    public function index(Request $request)
    {
        $userId = app('userId');
        $type = $request->input('type');
        $page_size = $request->input('page_size', 20);
        $search = $request->input('search');

        $list = Message::with(['content', 'userReadMessages' => function($query) use ($userId) {
                    $query->where('user_id', $userId);
                }])->when(isset($type), function($query) use ($type) {
                    $query->where('type', $type);
                })->whereIn('receive_user_id', [$userId, 0])
                ->when($search, function($query, $search) {
                    $query->where('title', '%' . $search . '%')
                        ->orWhere('descrition', '%' . $search . '%');
                })
                ->orderByDesc('created_at')
                ->paginate($page_size);
        
        $result = $list->map(function($item) use ($userId) {
            // 处理已读
            if ($item->userReadMessages->pluck('user_id')->search($userId) === false) {
                // 标记已读
                $item->userReadMessages()->save(new UserReadMessage([
                    'message_id' => $item->id,
                    'user_id' => $userId,
                ]));
            }
            if ($item->content && $item->content->exists) {
                $item->content = new ContentResource($item->content);
            }
            return new MessageResource($item);
        });

        return $this->okReturn([
            'pagination' => [
                'page' => $list->currentPage(),
                'page_size' => intval($page_size),
                'total' => $list->total(),
            ],
            'result' => $result,
        ]);
    }
}
